import axios from 'axios'

const Config = window.Config
// 最大请求次数
const defaultSettings = {
  type: 'post',
  url: '',
  data: '',
  dataType: 'json',
  timeout: 10000,
  headers: {},
  // contentType: 'application/x-www-form-urlencoded',
  withCredentials: false,
  delay: 0,

  baseURL: '',
  transformRequest: [],
  transformResponse: [],
  paramsSerializer: null,
  params: null,
  uploading: null,
  downloading: function () {},
  maxContentLength: 2000,
  validateStatus: null,
  auth: null,
  proxy: null,
  success: () => {},
  error: () => {},
  complete: () => {},
  // 请求次数，如果大于最大请求次数则会直接进入错误回调，防止无限循环
  requestCount: 1,
}

// 声明一个对象用来存储普通接口的取消函数
let cancels = {}

let params = {}

//请求拦截器
axios.interceptors.request.use(
  async (config) => {
    if (config.isAutoProxy) {
      if (token && typeof token === 'string') {
        config.headers.Authorization = `Bearer ${token}`
      }
    }

    return config
  },
  (error) => Promise.reject(error),
)
//响应拦截器
axios.interceptors.response.use(
  async function (response) {
    const { code } = response
    console.log('响应拦截器', response)

    if (response.config.isAutoDealError !== false) {
      if (code === 417) {
      } else if (code == 401) {
        const { responseText } = response
        const config = response.config
        localStorage.setItem('isLogin', '')
        // // 正在刷新token，返回一个未执行resolve的promise
        return new Promise((resolve) => {
          // 将resolve放进队列，用一个函数形式来保存，等token刷新后直接执行
          requests.push(() => {
            resolve(axios(config))
          })
        })
      }
    }

    return response
  },
  function (error) {
    console.log('响应拦截器2', error.response.data.errorCode)
    if (error.response.data.errorCode == 401) {
      localStorage.setItem('isLogin', '')
    }
    // 对响应错误做点什么
    return Promise.reject(error.response.data)
  },
)

async function commonAjax(options) {
  params = {
    url: options.url,
    method: options.type || 'POST',
    data: options.data,
    //axois默认不携带cookie
    withCredentials: true,
  }

  const { delay, error, success } = options

  return new Promise((resolve, reject) => {
    axios(params)
      .then((response) => {
        console.log('axois', response)

        const { status, message, data } = response
        if (status !== 200 && status !== 201) {
          reject(message)
          error && error(message)
        } else {
          success && success(data, response)
          resolve(data, response)
        }
      })
      .catch((err) => {
        reject(err)
      })
      .then(() => {})
  })
}

function ajaxAll(...args) {
  return Promise.all(...args)
}

export { commonAjax, ajaxAll }
